#include <windows.h>
#include <d3d11.h>
#pragma comment(linker, "/Merge:.rdata=.text")

#define DEFINE_GUIDW(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) const GUID DECLSPEC_SELECTANY name = { l, w1, w2, { b1, b2,  b3,  b4,  b5,  b6,  b7,  b8 } }
//DEFINE_GUIDW(IID_ID3D10Texture2D,0x9B7E4C04,0x342C,0x4106,0xA1,0x9F,0x4F,0x27,0x04,0xF6,0x89,0xF0);
DEFINE_GUIDW(IID_ID3D11Texture2D,0x6f15aaf2,0xd208,0x4e89,0x9a,0xb4,0x48,0x95,0x35,0xd3,0x4f,0x9c);

static const short WINDOW_HEIGHT = 600;
static const short WINDOW_WIDTH  = 800;

void __stdcall WinMainCRTStartup()
{
	ExitProcess(WinMain(GetModuleHandle(NULL), NULL, NULL, 1));
}

// Single entrypoint
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	static const WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_VREDRAW|CS_HREDRAW|CS_OWNDC, (WNDPROC) DefWindowProc, 0, 0, hInstance, 0, 0, 0, 0, "bdd", 0};

	RegisterClassEx(&wc);

	HWND hWnd = CreateWindow("bdd", "Origins - BigDaveDev(c) 2011", WS_OVERLAPPEDWINDOW, 100, 100, WINDOW_WIDTH, WINDOW_HEIGHT, 0, 0, hInstance, 0);
	ShowWindow(hWnd, nCmdShow);
	
	ID3D11Device *pd3dDevice;
	IDXGISwapChain *pSwapChain;
	ID3D11RenderTargetView *pRenderTargetView;
	ID3D11DeviceContext *pImmediateContext;

	const static DXGI_SWAP_CHAIN_DESC sd = {{WINDOW_WIDTH, WINDOW_HEIGHT, {60, 1}, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED, DXGI_MODE_SCALING_UNSPECIFIED}, {1, 0}, DXGI_USAGE_RENDER_TARGET_OUTPUT, 1, NULL, TRUE, DXGI_SWAP_EFFECT_SEQUENTIAL, 0};

	DXGI_SWAP_CHAIN_DESC temp;
	temp = sd;
	temp.OutputWindow = hWnd;

 	D3D11CreateDeviceAndSwapChain(
			NULL,
			D3D_DRIVER_TYPE_HARDWARE,
			NULL, 
			D3D11_CREATE_DEVICE_DEBUG,
			NULL,
			0,
			D3D11_SDK_VERSION,
			&temp,
			&pSwapChain,
			&pd3dDevice,
			NULL,
			&pImmediateContext);

	ID3D11Texture2D *pBackBuffer;
	pSwapChain->GetBuffer(0, (REFIID)IID_ID3D11Texture2D, (LPVOID*)&(pBackBuffer)) ;
	pd3dDevice->CreateRenderTargetView((ID3D11Resource*)pBackBuffer, NULL, &pRenderTargetView);
	pImmediateContext->OMSetRenderTargets(1, &pRenderTargetView, NULL );

	const static D3D11_VIEWPORT vp = {0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0, 1}; 
	pImmediateContext->RSSetViewports(1, &vp);

	OutputDebugString("Testing");

	while(!(::GetAsyncKeyState(VK_ESCAPE)))
	{
		static MSG msg;
		PeekMessage(&msg,hWnd,0,0,PM_REMOVE);

		static const float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f };
		pImmediateContext->ClearRenderTargetView(pRenderTargetView, ClearColor);

		pSwapChain->Present(0, 0);
	}

	pImmediateContext->ClearState();
	pd3dDevice->Release();
	pRenderTargetView->Release();
	pSwapChain->Release();	 
	pBackBuffer->Release();

	DestroyWindow(hWnd);

	UnregisterClass("bdd",hInstance);
	return 0;
}